import { request } from './request';

// 准备上传文件前获取文件路径
interface UploadInfo {
  mtyun: {
    token: string;
    key: string;
    data: string;
    bucket: string;
    url: string;
    backup_url: string;
    fop_url: string;
    fsizeLimit: number;
    quic_url: string;
    quic_idle_timeout: number;
    quic_crypto_timeout: number;
    ttl: number;
    access_url: string;
    chunk_size: number;
    connect_timeout: number;
    socket_timeout: number;
    thread_num: number;
    block_size: number;
    retry_strategy: null | any; // 可以根据实际结构进一步定义
  };
  order: string[];
}
export type GetUploadImageInfoResult = UploadInfo[];
export async function getUploadImageInfo<T = GetUploadImageInfoResult>() {
  return request<T, T>({
    url: 'https://strategy.app.meitudata.com/upload/policy',
    method: 'GET',
    params: {
      app: 'xiuxiu-pro',
      count: 1,
      suffix: 'jpeg',
      type: 'bizshoot',
    },
  });
}

// 上传文件
interface UploadImageResult {
  data: string; // 图片访问地址
  etag: string; // 文件的唯一标识
  fsize: string; // 文件大小（以字节为单位）
  mimeType: string; // 文件类型（MIME 类型）
  storage: string; // 存储位置标识
  type: string; // 文件所属业务类型
}
export async function uploadImageToCos<T = UploadImageResult>({
  token,
  file,
  key,
  fname,
}: {
  token: string;
  file: Blob;
  key: string;
  fname: string;
}) {
  return request<T, T>({
    url: 'https://up.meitudata.com/',
    method: 'POST',
    data: {
      token,
      file,
      key,
      fname,
    },
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}

// 获取抠图后的模版
interface GetImageMaskResult {
  reqid: string;
  // 0 表示成功
  code: number;
  data: {
    duration: {
      alg_process_time: number;
      created_timestamp: number;
      pull_timestamp: number;
      waiting_time: number;
      upload_time: number;
    };
    error_msg: string;
    msg_id: string;
    parameter: {
      Kind: number;
      bottom_x: string;
      bottom_y: string;
      exist_salient: boolean;
      process_time: number;
      pull_time: number;
      return_fe: boolean;
      rsp_media_type: string;
      top_x: string;
      top_y: string;
      use_fe: boolean;
      version: string;
    };
    extra: {
      [key: string]: any;
    };
    media_info_list: Array<{
      media_data: string;
      media_profiles: {
        media_data_type: string;
      };
      media_extra: {
        [key: string]: any;
      } | null;
    }>;
  };
}
export async function getImageMask<T = GetImageMaskResult>({
  source,
  client_id,
  gid,
}: {
  source: string;
  client_id: string;
  gid: string;
}) {
  return request<T, T>({
    url: 'https://webapi.designkit.com/v1/matting/sod_2c',
    method: 'POST',
    params: {
      client_id,
      gid,
      client_language: 'zh-Hans',
      country_code: 'CN',
    },
    data: {
      parameter: {
        rsp_media_type: 'url',
        nMask: true,
        // 商品货物
        model_type: 1,
        keep_resolution: false,
      },
      media_info_list: [
        {
          media_data: source,
          media_profiles: {
            media_data_type: 'url',
          },
        },
      ],
    },
  });
}

// 创建 ai 替换背景的操作
interface CreateAiReplaceBackgroundResult {
  reqid: string;
  code: number;
  message?: string;
  data: {
    id: number;
    url: string;
    mask_url: string;
    result_image_urls: string[];
    scene_result_images: string[];
    result_images: string[];
    process_status: number;
    finished_at: number;
    material_id: number;
    materials: any[];
    guidance_scale: number;
    steps: number;
    prompt_vs_refimage: number;
    refimage_url: string;
    prompt: string;
    user_material_id: number;
    product_category: string;
    angle: number;
    z_index: number;
    flip: number;
    box1: string;
    box2: string;
    scene_type: number;
    canvas_w: number;
    canvas_h: number;
    result_num: number;
    created_at: number;
    updated_at: number;
    uid: number;
    client_id: number;
    translate_prompt: string;
    commerce_task_id: number;
    commerce_subtask_ids: number[];
  };
}

export interface CreateAiReplaceBackgroundOptions {
  client_id: string;
  gid: string;
  prompt_vs_refimage: number;
  guidance_scale: number;
  steps: number;
  job_name: string;
  box1: string;
  box2: string;
  mask_url: string;
  url: string;
  category_id: number;
  product_category: string;
  projectID: number;
  refimage_url: string;
  clientOgroupid: number;
  clientOid: number;
}

export async function createAiReplaceBackground<T = CreateAiReplaceBackgroundResult>({
  client_id,
  gid,
  // 生图倾向
  prompt_vs_refimage,
  // 创意相关性
  guidance_scale,
  // 采用步骤
  steps,
  // 源文件名称,没有扩展名
  job_name,
  // 抠图后的模版尺寸,对应 x, y, w, h
  box1,
  // 比例调整后的模版尺寸,对应 x, y, w, h
  box2,
  // 抠图模版地址
  mask_url,
  // 源图像地址,
  url,
  // 分类的 id
  // 从 https://webapi.designkit.com/v2/ai_product/identify 接口获取
  category_id,
  // 分类
  // 从 https://webapi.designkit.com/v2/ai_product/identify 接口获取
  product_category,
  // 项目 id
  // 从 https://webapi.designkit.com/v1/user_history/func_project_create 接口获取
  projectID,
  // 背景参考图
  refimage_url,
  clientOgroupid,
  clientOid,
}: CreateAiReplaceBackgroundOptions) {
  return request<T, T>({
    url: 'https://webapi.designkit.com/v1/ai_product/create',
    method: 'POST',
    params: {
      operate_source: 'web',
      // C5F34252F04B6D50
      app_key: '',
      client_id,
      gid,
      client_language: 'zh-Hans',
      channel: '',
      country_code: 'CN',
      ts_random_id: '15c2f052-1004-4085-9ca8-bb4370389c63',
    },
    data: {
      batch_id: '',
      canvas_h: 400,
      canvas_w: 400,
      custom_stat: JSON.stringify({
        isMultiScene: 0,
        way: 'project_record',
        projectID: projectID,
        statTaskId: 'c9fe886c-acbf-4c20-9735-b1ad7220ad74',
        styleID: 999,
        preferReferenceBackgroundOrPromptEnabled: true,
        isUsedDeepSeek: false,
        isGpt4oScene: false,
      }),
      from_type: 'create',
      guidance_scale,
      identify_cate_id: category_id,
      is_portrait: 0,
      job_name,
      materials: [],
      multi_object: [
        {
          angle: 0,
          box1: box1,
          box2,
          flip: 0,
          mask_url,
          matting_type: 1,
          url,
          z_index: 0,
        },
      ],
      operate_source: 'web',
      product_category,
      project_id: projectID,
      prompt: '',
      prompt_neg: '',
      prompt_vs_refimage,
      refimage_url,
      scene_type: 2,
      seed: -1,
      steps: steps,
      transfer_id: '9D8B217B-3B01-4754-AC38-D70B1378E24F',
      snapshot_id: '556dbec3-304e-41f6-b17d-51f065e54dee',
      user_prompt: '',
    },
    headers: {
      'client-ogroupid': clientOgroupid,
      'client-oid': clientOid,
    },
  });
}

// 查询生成结果
export interface QueryCreateAiReplaceBackgroundResult {
  reqid: string;
  code: number;
  message?: string;
  data: {
    id: number;
    name: string;
    url: string;
    type: string;
    created_at: number;
    updated_at: number;
    subtasks: Array<{
      id: number;
      process_status: number;
      biz_request: string; // JSON 字符串，可根据需要进一步解析
      result_url: string;
      alg_id: string;
      name: string;
      ref_image: string;
      score: number;
      index: number;
      download_at: number;
      created_at: number;
      updated_at: number;
    }>;
  };
}
export interface QueryCreateAiReplaceBackgroundOptions {
  client_id: string;
  gid: string;
  id: number;
  alg_task_id: number;
  clientOgroupid: number;
  clientOid: number;
}
export async function queryCreateAiReplaceBackground<T = QueryCreateAiReplaceBackgroundResult>({
  client_id,
  gid,
  // 对应的是 create 的 commerce_task_id
  id,
  // 对应的是 create 的 id
  alg_task_id,
  clientOgroupid,
  clientOid,
}: QueryCreateAiReplaceBackgroundOptions) {
  return await request<T, T>({
    url: 'https://webapi.designkit.com/v1/ai_commerce/task/query',
    method: 'GET',
    params: {
      id: id,
      alg_task_id: alg_task_id,
      client_id: client_id,
      gid: gid,
      client_language: 'zh-Hans',
      channel: '',
      country_code: 'CN',
    },
    headers: {
      'client-ogroupid': clientOgroupid,
      'client-oid': clientOid,
    },
  });
}

// 获取分类
interface IdentifyResult {
  reqid: string;
  code: number;
  message?: string;
  data: {
    category_id: number;
    category_prompt: string;
    is_portrait: number;
    product_category: string;
  };
}
export async function identify<T = IdentifyResult>({
  client_id,
  gid,
  // 原图像地址
  url,
}: {
  client_id: string;
  gid: string;
  url: string;
}) {
  return request<T, T>({
    url: 'https://webapi.designkit.com/v2/ai_product/identify',
    method: 'POST',
    params: {
      client_id,
      gid,
      client_language: 'zh-Hans',
      country_code: 'CN',
      channel: '',
    },
    data: {
      url,
      is_portrait: 0,
    },
  });
}

// 创建项目
interface CreateProjectResult {
  reqid: string;
  code: number;
  message?: string;
  data: {
    project_id: number;
  };
}
export async function createProject<T = CreateProjectResult>({
  client_id,
  gid,
  // 源文件的文件名称
  name,
  // 源文件的文件地址
  imageUrl,
  category_id,
  product_category,
  maskUrl,
}: {
  client_id: string;
  gid: string;
  name: string;
  imageUrl: string;
  category_id: number;
  product_category: string;
  maskUrl: string;
}) {
  return request<T, T>({
    url: 'https://webapi.designkit.com/v1/user_history/func_project_create',
    method: 'POST',
    params: {
      client_id,
      gid,
      client_language: 'zh-Hans',
      country_code: 'CN',
      channel: '',
    },
    data: {
      func_type: 'aispt',
      name,
      origin_media: [
        {
          media_data: imageUrl,
          media_profiles: {
            media_data_size: 800,
            media_data_width: 800,
            media_data_height: 800,
            media_data_type: 'url',
          },
        },
      ],
      project_info: JSON.stringify({
        snapshotID: 'b2285ac5-fefd-43b4-92ae-058254153fcd',
        sceneType: 1,
        prompt: '',
        promptNeg: '',
        preferReferenceBackgroundOrPrompt: 0,
        preferReferenceBackgroundOrPromptEnabled: true,
        creativeRelevance: 1,
        samplingStepCount: 8,
        referenceBackgroundURL: '',
        replicationSceneImageURL: '',
        replicationSceneSimilarity: 0.5,
        replicationSceneEraserFlag: true,
        sceneIDs: [],
        color: '',
        isUsingColorScene: false,
        subjectCategoryName: product_category,
        subjectCategoryID: category_id,
        sceneCategoryTopID: category_id,
        originRatio: false,
        freeRatio: false,
        width: 400,
        height: 400,
        staticImageWidth: 800,
        staticImageHeight: 800,
        mainLayers: [
          {
            originURL: imageUrl,
            imageURL: imageUrl,
            mattingInfo: {
              mattingType: 1,
              maskURL: maskUrl,
              useBlurFilterRun: false,
              foregroundEstimateImageURL: '',
              maskUrl: maskUrl,
            },
            layerData: {
              rotate: 0,
              top: 60,
              left: 75.65495207667732,
              flipV: false,
              flipH: false,
              width: 248.69009584664536,
              zIndex: 0,
            },
          },
        ],
        materialLayers: [],
        extra: {
          fileName: name,
          isUsedDeepSeek: false,
          statTaskId: '331692e0-e766-4023-a416-c647e1e0bc77',
        },
      }),
    },
  });
}
